package com.shundr.auth.frame.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.shundr.auth.channel.R;
import com.shundr.auth.frame.constant.LConstants;
import com.shundr.auth.frame.util.LLogger;
import com.shundr.auth.frame.util.StringUtil;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

public class UpgradeService extends Service {
	private static final int NOTIFY_ID = 110;
	private int progress;
	private NotificationManager mNotificationManager;
	private boolean canceled;
	/**
	 * 下载地址
	 */
	private String saveFileName = LConstants.DOWNLOAD_APP_PATH
			+ "shundr_auth.apk";
	private DownloadBinder binder;
	private boolean serviceIsDestroy = false;
	/**
	 * 下载进度通知
	 */
	private Notification mNotification;
	/**
	 * 下载线程
	 */
	private Thread downLoadThread;

	private int lastRate = 0;

	private Context mContext = this;

	private String mUrl;
	private boolean isNotice = true;

	private Handler mHandler = new Handler() {

		@SuppressWarnings("deprecation")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			try {
				switch (msg.what) {
				case 0:
					// 下载完毕
					// 取消通知
					LLogger.e("下载完毕...");
					if (isNotice) {
						mNotificationManager.cancel(NOTIFY_ID);
						installApk();
					} else {
						stopSelf();
					}
					break;
				case 2:
					LLogger.e("取消通知...");
					// 取消通知
					if (isNotice) {
						mNotificationManager.cancel(NOTIFY_ID);
					}
					stopSelf();// 停掉服务自身
					break;
				case 1:
					LLogger.e("下载中...");
					if (isNotice) {
						int rate = msg.arg1;
						if (rate < 100) {
							RemoteViews contentview = mNotification.contentView;
							contentview.setTextViewText(R.id.tv_progress, rate
									+ "%");
							contentview.setProgressBar(R.id.progressbar, 100,
									rate, false);
						} else {
							// 下载完毕后变换通知形式
							mNotification.flags = Notification.FLAG_AUTO_CANCEL;
							mNotification.contentView = null;
							Intent intent = new Intent();
							// 告知已完成
							intent.putExtra("completed", "yes");
							// 更新参数,注意flags要使用FLAG_UPDATE_CURRENT
							PendingIntent contentIntent = PendingIntent
									.getActivity(mContext, 0, intent,
											PendingIntent.FLAG_UPDATE_CURRENT);
							mNotification.setLatestEventInfo(mContext, "下载完成",
									"文件已下载完毕", contentIntent);
							serviceIsDestroy = true;
							// stopSelf();// 停掉服务自身
							Message mMessage = mHandler.obtainMessage();
							mMessage.what = 0;
							mHandler.sendMessage(mMessage);
						}
						mNotificationManager.notify(NOTIFY_ID, mNotification);
					}
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		try {
			mUrl = intent.getStringExtra("url");
			isNotice = intent.getBooleanExtra("flag", true);
			binder = new DownloadBinder();
			mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
			// setForeground(true);
			// apkUrl=PrefUtils.getPrefString(mContext, "downUrl", "");
			if (StringUtil.isNull(mUrl)) {
				stopSelf();
			} else {
				binder.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		System.out.println("是否执行了 onBind");
		return binder;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// 假如被销毁了，无论如何都默认取消了。
		binder.cancel();
	}

	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}

	@Override
	public void onRebind(Intent intent) {
		super.onRebind(intent);
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	public class DownloadBinder extends Binder {
		public void start() {
			if (downLoadThread == null || !downLoadThread.isAlive()) {
				progress = 0;
				if (isNotice) {
					setNotification();
				}
				new Thread() {
					public void run() {
						// 下载
						startDownload();
					};
				}.start();
			}
		}

		public void cancel() {
			canceled = true;
		}

		public int getProgress() {
			return progress;
		}

		public boolean isCanceled() {
			return canceled;
		}

		public boolean serviceIsDestroy() {
			return serviceIsDestroy;
		}

		public void cancelNotification() {
			mHandler.sendEmptyMessage(2);
		}
	}

	private void startDownload() {
		canceled = false;
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}

	/**
	 * 安装apk
	 * 
	 * @param url
	 */
	private void installApk() {
		try {

			File apkfile = new File(saveFileName);
			if (!apkfile.exists()) {
				return;
			}
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
					"application/vnd.android.package-archive");
			mContext.startActivity(i);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				LLogger.e("larry : " + StringUtil.getUrlName(mUrl));
				if (isNotice) {
					saveFileName = LConstants.DOWNLOAD_APP_PATH
							+ StringUtil.getUrlName(mUrl);
				} else {
					saveFileName = LConstants.DOWNLOAD_APP_PATH + "splash.png";
				}

				URL url = new URL(mUrl);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();
				File file = new File(LConstants.DOWNLOAD_APP_PATH);
				if (!file.exists()) {
					file.mkdirs();
				}
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					Message msg = mHandler.obtainMessage();
					msg.what = 1;
					msg.arg1 = progress;
					if (progress >= lastRate + 1) {
						mHandler.sendMessage(msg);
						lastRate = progress;
					}
					if (numread <= 0) {
						// 下载完成通知安装
						mHandler.sendEmptyMessage(0);
						// 下载完了，cancelled也要设置
						canceled = true;
						break;
					}
					fos.write(buf, 0, numread);
				} while (!canceled);// 点击取消就停止下载.

				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	};

	@SuppressWarnings("deprecation")
	private void setNotification() {
		try {
			int icon = R.drawable.ic_launcher;
			CharSequence tickerText = "开始下载";
			long when = System.currentTimeMillis();
			mNotification = new Notification(icon, tickerText, when);
			// 放置在"正在运行"栏目中
			mNotification.flags = Notification.FLAG_ONGOING_EVENT;
			RemoteViews contentView = new RemoteViews(getPackageName(),
					R.layout.view_download_notification);
			contentView.setTextViewText(R.id.tv_appname, getResources()
					.getString(R.string.app_name) + ".apk 正在下载...");
			// 指定个性化视图
			mNotification.contentView = contentView;
			Intent intent = new Intent();
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
					intent, PendingIntent.FLAG_UPDATE_CURRENT);
			// 指定内容意图
			mNotification.contentIntent = contentIntent;
			mNotificationManager.notify(NOTIFY_ID, mNotification);
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
	}
}
